import React, { useState, useEffect } from 'react'
import { Table, Tag, Button, Modal, notification } from 'antd'
// import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import axios from 'axios';
import Item from 'antd/lib/list/Item';
// const { confirm } = Modal

export default function AuditList(props) {
  const [dataSource, setDataSource] = useState([]);

  const { username } = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    axios(`/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`).then(res => {
      console.log(res.data)
      setDataSource(res.data)
    })
  }, [username])

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'name',  // 可写可不写
      render: (title, Item) => <a href={`#/news-manage/preview/${Item.id}`}>{title}</a>
    },
    {
      title: '作者',
      dataIndex: 'title',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => <div>{category.title}</div>
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        const colorList = ["", "orange", "green", "red"]
        const auditList = ["草稿箱", "审核中", "已通过", "未通过"]
        return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
      }
    },
    {
      title: '操作',
      render: (Item) => <div>
        {Item.auditState === 1 && <Button type="primary" onClick={() => handlePublish(Item)}>发布</Button>}
        {Item.auditState === 2 && <Button type="primary" onClick={() => handleRervert(Item)}>撤销</Button>}
        {Item.auditState === 3 && <Button type="primary">更新</Button>}
      </div>
    },
  ];

  const handlePublish = (Item) => {
    axios.patch(`/news/${Item.id}`, {
      'auditState': 2,
      'publishTIme': Date.now()
    }).then(res => {
      props.history.push('/publish-manage/published')
      notification.info({
        message: `通知`,
        description: `您可以到【发布管理/已经发布】中查看你的新闻`,
        placement: 'bottomRight',
      });
    })
  }

  const handleRervert = (Item) => {
    setDataSource(dataSource.filter(data => data.id !== Item.id))
    axios.patch(`/news/${Item.id}`, {
      auditState: 0
    }).then(res => {
      notification.info({
        message: `通知`,
        description: `您可以到草稿箱中查看你的新闻`,
        placement: 'bottomRight',
      });
    })
  }

  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 5
        }}
        rowKey={Item => Item.id}
      />
    </div>
  )
}
